<template>
  <div v-loading="loading">
    <el-form ref="form" :model="form" :rules="rules" label-width="120px" class="dataForm">
      <el-row>
        <el-col :span="24">
          <el-form-item :label="$t('申请标题')" prop="actTitle">
            <el-input v-model="form.actTitle" :placeholder="$t('申请标题')" show-word-limit maxlength="100" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('合伙企业名称')" prop="name">
            <el-autocomplete
              v-model="form.name"
              class="inline-input name"
              :fetch-suggestions="companyQuerySearch"
              :placeholder="$t('合伙企业名称')"
              :trigger-on-focus="false"
              :maxlength="100"
              @select="companyHandleSelect"
            >
              <template v-if="enableTyc" slot="append">
                <a @click="companyHandleSelect">{{ $t('查询工商信息') }}</a>
              </template>
            </el-autocomplete>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('执行事务合伙人')" prop="executivePartner">
            <el-input v-model="form.executivePartner" :placeholder="$t('执行事务合伙人')" show-word-limit maxlength="100" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('执行事务合伙人委派代表')" prop="appoints">
            <el-input v-model="form.appoints" :placeholder="$t('执行事务合伙人委派代表')" show-word-limit maxlength="100" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('成立时间')" prop="established">
            <DatePicker
              v-model="form.established"
              :placeholder="$t('成立时间')"
            />

          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('企业统一社会信用代码')" prop="creditCode">
            <el-input v-model="form.creditCode" :placeholder="$t('企业统一社会信用代码')" show-word-limit maxlength="100" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('执照登记日期')" prop="registerDate">
            <DatePicker
              v-model="form.registerDate"
              :placeholder="$t('执照登记日期')"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('合伙期限')" prop="partnershipTerm">
            <el-input v-model="form.partnershipTerm" :placeholder="$t('合伙期限')" :maxlength="50" show-word-limit />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('基本户')" prop="baseAccount">
            <el-input v-model="form.baseAccount" :placeholder="$t('基本户')" show-word-limit maxlength="100" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('经营场所')" prop="businessPlace">
            <el-input v-model="form.businessPlace" :placeholder="$t('经营场所')" show-word-limit maxlength="100" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('经营范围')" prop="businessRange">
            <el-input v-model="form.businessRange" :placeholder="$t('经营范围')" show-word-limit maxlength="100" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('基金管理人')" prop="gpId">
            <MainBodySelect
              v-model="form.gpId"
              parameters="manager"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('是否备案')" prop="record">
            <dict-select
              v-model="form.record"
              dictionary="yes_no_record"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('变更日期')" prop="changeDate">
            <DatePicker
              v-model="form.changeDate"
              :placeholder="$t('变更日期')"
            />

          </el-form-item>
        </el-col>
      </el-row>
      <div class="area-header">
        <span class="area-header-title">{{ $t('股东信息') }}</span>
      </div>
      <el-table :data="form.hhqyChangeShareholders" class="nowrapTable formTable" border>
        <el-table-column :label="$t('股东名称')" prop="name" align="center">
          <template slot-scope="scope">
            <el-autocomplete
              v-model="scope.row.name"
              :fetch-suggestions="(queryString, cg) => querySearch(queryString, cg, scope.$index)"
              :placeholder="$t('股东名称')"
              @select="shareholderOnSelect($event, scope.$index)"
            />
          </template>
        </el-table-column>
        <el-table-column :label="$t('持股比例(%)')" prop="shareholdingRatio" align="center">
          <template slot-scope="scope">
            <Ratio v-model="scope.row.shareholdingRatio" :precision="2" :controls="false" :max="100" />
          </template>
        </el-table-column>
        <el-table-column :label="$t('投资金额') + $t('金额单位')" prop="investAmount" align="center">
          <template slot-scope="scope">
            <Money v-model="scope.row.investAmount" unit="w" />
          </template>
        </el-table-column>
        <el-table-column :label="$t('操作')" width="100" align="center">
          <template slot-scope="scope">
            <el-button size="mini" type="text" icon="el-icon-delete" @click="delShareholder(scope.$index)">{{ $t('删除') }}</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="tol">
        <el-button type="primary" icon="el-icon-plus" size="mini" @click="addShareholder">{{ $t("添加") }}</el-button>
      </div>
    </el-form>
    <div slot="footer" class="dialog-footer" style="text-align: right;">
      <!--保存，保存并启动流程，取消 三个按钮-->
      <FormBtn ref="formBtn" :bus-data="form" has-permi="hhqy:changehistory" :menu-key="menuKey" />
    </div>
  </div>
</template>

<script>
    import { saveHhqyChangeHistory, getHhqyChangeHistory, getLastChangeShareHolder } from '@/api/hhqy/changehistory/hhqyChangeHistory'
    import { companyListByName } from '@/api/company/base/companyBase'
    import MainBodySelect from '@/components/MainBodySelect'
    import { Notification } from 'element-ui'
    import { getHhqyDetail, shareholdersList, getHhqyBase } from '@/api/hhqy/base/hhqyBase'
    export default {
      components: {
        MainBodySelect
      },
        data() {
            return {
              enableTyc: undefined,
              // 菜单标识
              menuKey: 'hhqy_change_history',
                // 表单参数
                form: {
                  hhqyChangeShareholders: []
                },
              // 股东名称列表数据
              restaurants: [],
                // 表单校验
                rules: {
                  hhqyId: [
                    { required: true, message: this.$t('必填信息'), trigger: 'blur' }
                  ], name: [
                    { required: true, message: this.$t('必填信息'), trigger: 'blur' }
                  ], executivePartner: [
                    { required: true, message: this.$t('必填信息'), trigger: 'blur' }
                  ], baseAccount: [
                    { required: true, message: this.$t('必填信息'), trigger: 'blur' }
                  ], changeDate: [
                    { required: true, message: this.$t('必填信息'), trigger: 'blur' }
                  ], actTitle: [
                    { required: true, message: this.$t('必填信息'), trigger: 'blur' }
                  ]
                },
                // 遮罩层
                loading: false,
                // 操作按钮默认不展示
                buttonShow: true,
              // 天眼查查询条件
              tycParam: {
                id: '',
                companyName: '',
                tycId: ''
              }
            }
        },
        created() {
            this.$bus.$emit('async_done')
        },
      mounted() {
        this.enableTyc = (window.localStorage.getItem('enableTyc') === 'true')
        shareholdersList().then(response => {
          this.restaurants = response.rows.map((ele) => { return { value: ele.name, id: ele.id } })
        })
      },
      methods: {
            // 初始化数据
            init(data) {
              this.loading = true
                if (data != null && data.id !== undefined) {
                    getHhqyChangeHistory(data.id).then(response => {
                        this.form = response.data
                      this.loading = false
                    })
                } else {
                    this.reset()
                    getHhqyBase(this.$route.query.id).then(response => {
                      this.form = response.data
                      this.form.hhqyId = this.form.id
                      this.form.id = undefined
                      getLastChangeShareHolder(this.$route.query.id).then(response => {
                        if (response.data) {
                          this.form.hhqyChangeShareholders = response.data.hhqyChangeShareholders
                        }
                        this.loading = false
                      })
                    })
                }
            },
            // 表单重置
            reset() {
                this.form = {
                id: undefined,
                hhqyId: undefined,
                name: undefined,
                executivePartner: undefined,
                appoints: undefined,
                established: undefined,
                creditCode: undefined,
                registerDate: undefined,
                partnershipTerm: undefined,
                baseAccount: undefined,
                businessPlace: undefined,
                businessRange: undefined,
                remark: undefined,
                delFlag: undefined,
                createBy: undefined,
                updateBy: undefined,
                createTime: undefined,
                updateTime: undefined,
                actId: undefined,
                actStatus: '0',
                actTitle: undefined
                }
                this.resetForm('form')
            },
            // 取消按钮
            cancel() {
                this.$parent.$parent.formOpen = false
                this.$parent.$parent.reset()
            },
            // 关闭form页面
            closeForm() {
                // 关闭form页面遮罩层
                this.loading = false
                // 关闭form页面
                this.$parent.$parent.formOpen = false
                // 刷新list页面
                this.$parent.$parent.getList()
            },
            /** 提交按钮 */
            submitForm: function(type) {
                this.$refs['form'].validate(valid => {
                    // 验证数据
                    if (valid) {
                        // 弹出遮罩层
                        this.loading = true
                        // 保存数据
                        saveHhqyChangeHistory(this.form).then(response => {
                            if (response.code === 200) {
                                // 点击的按钮是保存并启动流程
                                if (type === 'process') {
                                    // 启动流程
                                    this.startProcess(response.data.id)
                                // 点击的仅保存
                                } else {
                                    this.msgSuccess(this.$t('保存成功'))
                                    // 关闭form页面
                                    this.closeForm()
                                }
                            } else {
                                this.msgError(response.msg)
                                this.loading = false
                            }
                        })
                    } else {
                      this.locationError(document)
                    }
                })
           },
            // 启动流程
           startProcess: function(dataId) {
               this.loading = false
               // 启动流程时候传入的参数
               const processData = {}
               // 待办标题
               processData.title = '「' + this.form.name + '」' + ':' + this.form.actTitle
               // 业务表名
               processData.dataTable = 'hhqy_change_history'
               // 业务ID
               processData.dataId = dataId
               // 业务表单地址(待办页面需要打开的页面)
               processData.formPath = '@/views/hhqy/changehistory/hhqyChangeHistoryForm'
               processData.viewPath = '@/views/hhqy/changehistory/hhqyChangeHistoryView'
               // 菜单标识(根据菜单标识判断的走哪个流程)
               processData.menuKey = this.menuKey
               this.startProcessByMenu(processData, () => {
                   this.form.actStatus = 'D'
                   this.msgSuccess(this.$t('数据保存成功,流程启动成功'))
                   this.closeForm()
               })
           },
          // 标的公司查询
          companyQuerySearch(queryString, cb) {
            companyListByName(queryString).then(res => {
              if (res.code === 200) {
                cb(res.data)
              }
            })
          },
          // 标的公司选择后事件
          companyHandleSelect(item) {
            this.loading = true
            var name = this.form.name
            if (name === '' || name === undefined) {
              Notification.error({
                title: this.$t('请先输入公司全称！')
              })
              this.loading = false
              return
            }
            this.resetForm()
            this.tycParam.id = this.form.id
            this.tycParam.tycId = item.id
            this.tycParam.name = name
            getHhqyDetail(this.tycParam).then(res => {
              if (res.code === 200) {
                if (res.msg === 'exist') {
                  this.form.mediationName = undefined
                  Notification.error({
                    title: this.$t('合伙企业全称已存在！')
                  })
                  this.loading = false
                } else if (res.msg === 'nofind') {
                  this.form.companyName = undefined
                  Notification.error({
                    title: this.$t('天眼查没有获取到该合伙企业信息！')
                  })
                  this.loading = false
                } else {
                  // 公司简称
                  this.form.name = name
                  // 企业统一社会信用代码
                  this.form.creditCode = res.data.creditCode
                  // 成立时间
                  this.form.established = res.data.established
                  // 天眼查ID
                  this.form.tycId = res.data.tycId
                  this.msgSuccess(this.$t('已获取工商信息！'))
                  this.loading = false
                }
              }
            })
          },
          // 初始化天眼查获取的数据
          resetForm() {
            this.form.name = undefined
            this.form.creditCode = undefined
            this.form.estiblishTime = undefined
            this.form.tycId = undefined
          },
          addShareholder() {
            const row = {
              id: undefined,
              name: '',
              shareholdingRatio: undefined,
              investAmount: undefined
            }
            if (!(this.form.hhqyChangeShareholders instanceof Array)) {
              this.$set(this.form, 'hhqyChangeShareholders', [])
            }
            this.$nextTick(() => {
              this.form.hhqyChangeShareholders.push(row)
            })
          },
          delShareholder(index) {
              this.form.hhqyChangeShareholders.splice(index, 1)
          },
          querySearch(queryString, cb, index) {
            var restaurants = this.restaurants
            var results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants
            if (results.length === 0) {
              this.form.hhqyChangeShareholders[index].shareholderId = undefined
            }
            // 调用 callback 返回建议列表的数据
            cb(results)
          },
          createFilter(queryString) {
            return (restaurant) => {
              return (restaurant.value.toLowerCase().includes(queryString.toLowerCase()))
            }
          },
          shareholderOnSelect(val, index) {
            this.form.hhqyChangeShareholders[index].shareholderId = val.id
          }
        }
    }
</script>
